<template>
  <el-dialog title="上传文件" :visible.sync="option.isShow" width="70%" :lock-scroll="false" @open="openHandle" @close="closeHandle">
    <el-card v-loading="loading">
      <el-form :model="ruleForm" size="small" label-position="left" label-width="80px" ref="ruleForm">
          <el-row :gutter="10">
            <el-col :lg="12" :md="12">
              <el-form-item label="渠道" prop='CHANNELTYPE'>
                <el-select v-model="ruleForm.CHANNELTYPE" filterable @change="changeChannel" placeholder="请选择业务渠道">
                  <el-option v-for="item in option.channelOption" :key="item.FIELDKEY" :label="item.FIELDVALUE"
                    :value="item.FIELDKEY"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
      </el-form>
      <el-upload ref="upload" :action="fileUrl" :file-list="fileList" :limit="1" :on-exceed="handleExceed" :on-change="handleChange" :on-success="successCallback" :auto-upload="false" :on-error="handleError">
        <el-button slot="trigger" size="small" type="primary" :disabled="ruleForm.CHANNELTYPE == ' '">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" :disabled="enable" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传txt文件，且不超过5MB</div>
      </el-upload>
      <!-- <el-table ref="tableData" :data='outputJSON' header-row-class-name="tableHeaderClass" border style="margin:10px 0 0 0">
        <el-table-column prop='SESSIONID' label='会话ID'></el-table-column>
        <el-table-column prop='CUSTOMER' label='客户姓名'></el-table-column>
        <el-table-column prop='CUSTOMLEVEL' label='客户等级'></el-table-column>
        <el-table-column prop='TELNUMBER' label='电话号码'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='CUSTOMIDTYPE' label='客户身份证类型'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='CUSTOMIDNO' label='客户身份证号'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='CALLTYPE' label='呼叫类型'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='AREA' label='运营地区' ></el-table-column>
        <el-table-column prop='AGENTID' label='坐席ID'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='AGENTNAME' label='坐席姓名'></el-table-column>
        <el-table-column prop='AGENTLEVEL' label='坐席星级'></el-table-column>
        <el-table-column prop='EXTNO' label='分机号'></el-table-column>
        <el-table-column prop='TEAM' label='班组'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='SKILL' label='技能组'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='MEDIATYPE' label='多媒体类型'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='CHANNELTYPE' label='渠道类型'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='BEGINTIME' label='会话开始时间'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='ENDTIME' label='会话结束时间'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='SESSIONTIME' label='会话持续时长'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='BRNO' label='机构号'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='CUSTEVAUATE' label='满意度'  :formatter="dataFormat"></el-table-column>
        <el-table-column prop='BUSINESSTYPE' label='业务类型'  :formatter="dataFormat"></el-table-column>
      </el-table> -->
    </el-card>
    <span slot="footer" class="dialog-footer">
      <el-button @click="saveImportData" type="primary" size="mini">保存</el-button>
      <el-button @click="option.isShow=false" size="mini">取 消</el-button>
    </span>
  </el-dialog>
</template>
<script>
import request from "@/common/utils/requestQC";
import fileAdd from "@/message/QCManage/dataCollectionManage/dataImport/dataImport";
import getGlobalParams from "@/common/utils/getGlobalParams";


export default {
  
  props: ['option'],
  data() {
    return {
      ruleForm:{
        FILENAME: '',
        CHANNELTYPE:'',
      },
       rules: {
          CHANNELTYPE: [{
            required: true,
            message: '请选择渠道',
            trigger: 'change'
          }],
       },
      deptMap:{},
      'mediaList': {
          '00': '电话',
          '01': '视频',
          '02': '文字',
        },
      "LOGINFLG": {
          "1": "1-密码",
          "0": "0-指纹",
        },
        "AGENTSEX": {
          "1": "1-男",
          "2": "2-女",
        },
        "STAFSTS": {
          "01": "试用",
          "02": "正式上岗"
        },
         "AGENTLEVEL": {
          "1": "1-一星",
          "2": "2-二星",
          "3": "3-三星",
          "4": "4-四星",
          "5": "5-五星",
        },
         "AGENTROLE": {
          "01": "01-普通坐席",
          "02": "02-组长",
          "03": "03-班长",
          // "04": "04-坐席主管",
          // "05": "05-坐席经理",
          // "06": "06-质检员",
          // "07": "07-质检主管",
          // "08": "08-培训师",
          // "09": "09-培训主管",
          // "10": "10-排班师",
          // "11": "11-排班主管",
          // "12": "12-知识库普通用户",
          // "13": "13-知识库管理员"
        },
        STAFSTSLIST: [{
            name: '试用',
            value: '01'
          },
          {
            name: '正式上岗',
            value: '02'
          },
        ],
        nowDate:'',
      fileUrl: "",
      fileList: [],
      filepath: "",
      fileDownUrl: "",
      enable: true,
      loading: false,
      outputJSON: [],
      queryBtn: false
    };
  },
  created() {
    let date = new Date()
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDate()
      month = month < 10 ? '0' + month : month
      day = day < 10 ? '0' + day : day
       this.nowDate = year + '' + month + '' + day;
    // 获取版本上传地址
    this.fileUrl = getGlobalParams.get("FileUploadAddress");
    this.filepath = getGlobalParams.get("ExcelPath");
    // this.fileDownUrl = getGlobalParams.get("KnowledgeFileDownloadAddress");
  },
  methods: {
    changeChannel(){
      // this.fileUrl += '/'+this.ruleForm.CHANNELTYPE+'/'+this.nowDate
    },
    
    dataFormat(row, column) {
        if (column.property == "坐席等级")
          return this.AGENTLEVEL[row[column.property]];
        if (column.property == "登录方式")
          return this.LOGINFLG[row[column.property]];
        if (column.property == "性别")
          return this.AGENTSEX[row[column.property]];
        // if (column.property == "ENGLEVEL")
        //   return this.ENGLEVEL[row[column.property]];
        if (column.property == "班")
          return this.deptMap[row[column.property]];
        if (column.property == "角色")
          return this.AGENTROLE[row[column.property]];
        if (column.property == "组名")
          return this.deptMap[row[column.property]];
        if (column.property == "人员状态")
          return this.STAFSTS[row[column.property]];
        if (column.property == "受理渠道")
          return this.mediaFormat(row[column.property]);
      },
      // 过滤渠道
      mediaFormat(str) {
        let value = []
        let arr = str.split('|')
        arr.forEach(item => {
          value.push(this.mediaList[item])
        })
        return value.join(',')
      },
    openHandle() {
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    // 大于一个文件提示信息
    handleExceed(files, fileList) {
      this.$message.warning(`只能上传一个文件！`);
    },
    async saveImportData(){
      this.loading = true;
      let resBody = new fileAdd();
      resBody.data.COLLECTFLAG = '1' //1-手动导入
      resBody.data.FILENAME =this.ruleForm.FILENAME;
      // resBody.data.FILENAME =this.ruleForm.CHANNELTYPE+'/'+this.nowDate+'/'+this.ruleForm.FILENAME;
      resBody.data.BATCHDATE = this.nowDate
      resBody.data.CHANNELTYPE = this.ruleForm.CHANNELTYPE
      let response = await request(resBody);
      this.loading = false;
      if (response.SYS_HEAD.ReturnCode == "000000") {
        this.$message({
          type: "success",
          message: "导入成功"
        });
        this.option.isShow = false
        this.$emit("refreshTable1");
      } else {
        this.fileList = [];
        this.$message({
          type: "error",
          message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
        });
      }
    },
    // 上传成功的回调
    async successCallback(val, file) {
      // console.log(val);
      // console.log("this.filepath", this.filepath);
      this.ruleForm.FILENAME = file.name
     
    },
    handleError() {
      this.$message.warning(`文件上传失败！`);
    },
    closeHandle() {
      this.initPop();
      this.enable = true;
    },

    initPop() {
      this.outputJSON = [];
      this.queryBtn = false;
      this.fileList = [];
    },
    handleChange(file, fileList) {
      // console.log(file)
      var vueIns = this;
      var IMPORTFILE_MAXSIZE = 1 * 5120;
      const isLt5M = file.size / 1024 < IMPORTFILE_MAXSIZE;
      //控制导入文件大小
      //判断是否有文件
      if (!file) {
        vueIns.$message({
          message: "请选择文件",
          type: 'error  '
        });
        vueIns.outputJSON = [];
        return
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!');
        vueIns.outputJSON = [];
        file = "";
        this.fileList = [];
        return
      }
      //判断格式
      // console.log(fileData);
      var tempArr = file.name.split(".");
      var suffix = tempArr[tempArr.length - 1];
      if (suffix != 'txt' ) {
        vueIns.$message({
          message: "文件格式不正确",
          type: 'error  '
        });
        vueIns.outputJSON = [];
        file = "";
        this.fileList = [];
        return
      }
      // var reader = new FileReader();
      // reader.onloadend = async function(e) {
      //   var data = e.target.result;
      //   var workbook = vueIns.XLSX.read(data, { type: 'binary' });
      //   var sheetObject = workbook.Sheets[workbook.SheetNames[0]];
      //   delete sheetObject.A1;
      //   var temp = JSON.parse(JSON.stringify(vueIns.XLSX.utils.sheet_to_json(sheetObject)));
      //   var outPutArr = [];
      //   temp.splice(0, 1);
      //   console.log("outPutArr", temp);
      //   for (var i = 0; i < temp.length; i++) {
      //     var quesContent = new Object();
      //     quesContent.NO = temp[i].__EMPTY;
      //     quesContent['坐席工号'] = temp[i].__EMPTY_1;
      //     quesContent['姓名'] = temp[i].__EMPTY_2;
      //     quesContent['班'] = temp[i].__EMPTY_3;
      //     quesContent['组名'] = temp[i].__EMPTY_4;
      //     quesContent['角色'] = temp[i].__EMPTY_5;
      //     quesContent['坐席等级'] = temp[i].__EMPTY_6;
      //     quesContent['受理渠道'] = temp[i].__EMPTY_7;
      //     quesContent['人员状态'] = temp[i].__EMPTY_8;
      //     quesContent['联系方式'] = temp[i].__EMPTY_9;
      //     quesContent['邮箱'] = temp[i].__EMPTY_10;
      //     quesContent['性别'] = temp[i].__EMPTY_11;
      //     quesContent['登录方式'] = temp[i].__EMPTY_12;
      //     // if (temp[i].__EMPTY_3) {
      //     //   quesContent.CHANNEL = temp[i].__EMPTY_3;
      //     // } else {
      //     //   quesContent.CHANNEL = "";
      //     // }
      //     // quesContent.ANWSERTYPE = temp[i].__EMPTY_4;
      //     // quesContent.ANWSERVALUE = temp[i].__EMPTY_5;
      //     outPutArr.push(
      //       quesContent
      //     );
      //   }
      //   if (outPutArr[0]['坐席工号'] && outPutArr[0]['姓名'] && outPutArr[0]['班'] && outPutArr[0]['组名'] && outPutArr[0]['角色']&& outPutArr[0]['坐席等级']&& outPutArr[0]['受理渠道']&& outPutArr[0]['人员状态']&& outPutArr[0]['联系方式']&& outPutArr[0]['邮箱']) {
      //     vueIns.outputJSON = outPutArr;
      //     console.log(vueIns.outputJSON);
      //     vueIns.queryBtn = true;
          vueIns.enable = false;
      //   }
      //   else {
      //     vueIns.$message({
      //       message: "请遵循对应格式",
      //       type: 'error  '
      //     });
      //     vueIns.outputJSON = [];
      //     return
      //   }
      // };
      // reader.readAsBinaryString(file.raw);
    }
  }
};
</script>

<style scoped>

</style>
